import React from 'react'
import { useNavigate } from 'react-router-dom';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import { Form, Input, Button, message } from "antd";
import { checkOldPwd, editPassword } from "@/api/users";
import { useSelector, useDispatch } from "react-redux";
import { changeInfor } from "@/store/userSlice";

export default function AccountEdit() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { id } = useSelector((state) => state.user.userInfor);
  const dispatch = useDispatch();
  const onFinish = async values => {
    const res = await checkOldPwd({ id, oldPwd: values.oldPwd });
    if (res.code === 0) {
      const { code, msg } = await editPassword({ newPwd: values.newPwd, id, oldPwd: values.oldPwd });
      if (code === 0) {
        message.success(msg);
        // 清空表单
        form.resetFields();
        //清除用户信息
        sessionStorage.removeItem('user');
        //清除pinia中的用户信息
        dispatch(changeInfor({}));
        //跳转到登录页面
        navigate('/');
      }
    } else {
      message.error('原密码错误');
      // 清空表单
      form.resetFields();
    }
  };
  const onFinishFailed = () => {
    message.error('请先输入必填项');
  };

  return (
    <>
      <ContentTitle title="修改密码" />
      <Form
        name="basic"
        form={form}
        style={{ marginTop: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="旧密码"
          name="oldPwd"
          rules={[{ required: true, message: '请输入旧密码!' }]}
        >
          <Input.Password autoComplete='off' />
        </Form.Item>

        <Form.Item
          label="新密码"
          name="newPwd"
          rules={[{ required: true, message: '请输入新密码!' }]}
        >
          <Input.Password autoComplete='off' />
        </Form.Item>

        <Form.Item
          label="确认新密码"
          name="cekPwd"
          rules={[{ required: true, message: '请确定新密码!' }]}
        >
          <Input.Password autoComplete='off' />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            修改密码
          </Button>
        </Form.Item>
      </Form>
    </>
  )
}
